using System;
using System.Collections.Generic;
using Rilisoft.MiniJson;
using UnityEngine;

public class SaleController : MonoBehaviour
{
	public static SaleController instance;

	public List<SaleInfo> listSaleProduct = new List<SaleInfo>();

	private DateTime curServerTime;

	private void Awake()
	{
		instance = this;
	}

	private void OnDestroy()
	{
		instance = null;
		ClearProductSaleInfo();
	}

	private void Start()
	{
		ParseData(JSONManager.Instance.GetJSON(URLs.Sale));
	}

	private void ParseData(string text)
	{
		if (text.Equals(string.Empty))
		{
			return;
		}
		Dictionary<string, object> dictionary = Json.Deserialize(text) as Dictionary<string, object>;
		if (dictionary == null)
		{
			BCWDebug.LogError("Break - saleData = null", "Sales");
			return;
		}
		int num = 0;
		int num2 = 0;
		if (dictionary.ContainsKey("start"))
		{
			num = int.Parse(dictionary["start"].ToString());
		}
		if (dictionary.ContainsKey("duration"))
		{
			num2 = int.Parse(dictionary["duration"].ToString());
		}
		if (num == 0 || num2 == 0)
		{
			BCWDebug.LogError("Break - timeStart == 0 || timeDuration == 0", "Sales");
			return;
		}
		bool flag = false;
		if (dictionary.ContainsKey("is_active"))
		{
			int num3 = int.Parse(dictionary["is_active"].ToString());
			flag = num3 == 1;
		}
		if (!flag)
		{
			return;
		}
		GetServerTime();
		if (!(curServerTime >= GetCurrentTimeByUnixTime(num)) || !(curServerTime <= GetCurrentTimeByUnixTime(num + num2)))
		{
			return;
		}
		List<object> list = dictionary["sale_products"] as List<object>;
		if (list != null)
		{
			listSaleProduct = new List<SaleInfo>();
			for (int i = 0; i < list.Count; i++)
			{
				Dictionary<string, object> dictionary2 = list[i] as Dictionary<string, object>;
				if (dictionary2 != null)
				{
					SaleInfo saleInfo = new SaleInfo();
					if (dictionary2.ContainsKey("id"))
					{
						saleInfo.id = (string)dictionary2["id"];
					}
					if (dictionary2.ContainsKey("percent"))
					{
						saleInfo.percent = Convert.ToInt32((long)dictionary2["percent"]);
					}
					listSaleProduct.Add(saleInfo);
				}
			}
		}
		SetProductSaleInfo();
	}

	public static DateTime GetCurrentTimeByUnixTime(int unixTime)
	{
		return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(unixTime);
	}

	private void GetServerTime()
	{
		if (JSONManager.Instance.ServerTimeLoad())
		{
			curServerTime = GetCurrentTimeByUnixTime(JSONManager.Instance.GetServerTime());
		}
		else
		{
			curServerTime = DateTime.UtcNow;
		}
	}

	private void SetProductSaleInfo()
	{
		if (listSaleProduct != null)
		{
			listSaleProduct.ForEach(delegate(SaleInfo p)
			{
				MarketController.Instance.SetProductSaleInfo(p.id, p.percent);
			});
		}
	}

	private void ClearProductSaleInfo()
	{
		if (listSaleProduct != null)
		{
			listSaleProduct.ForEach(delegate(SaleInfo p)
			{
				MarketController.Instance.SetProductSaleInfo(p.id, 0f);
			});
		}
	}
}
